package org.createModel.singleton.demo7;

import java.io.Serializable;

/**
 * 通过反射破坏单例模式
 */
public class Singleton implements Serializable {
    private Singleton() {}

    // volatile 防止指令重排
    private static volatile Singleton instance;

    public static Singleton getInstance() {
        // 首次检查
        if (instance == null) {
            synchronized (Singleton.class) {
                // 二次判断
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

    // 解决序列号单例问题
    public Object readResolve() {
        return instance;
    }
}
